/**
 * 报销单头信息
 */
import React from 'react';
import moment from 'moment'
import { connect } from 'react-redux'
import { messages, queryCurrencyPrecision, getQueryUrlParam, addCalculate } from "share/common";
import {Row, Modal, Button, Tag, DatePicker, Icon, Spin, Tooltip, Popover} from "antd"

import constants from 'share/constants'
import Skeleton from 'components/skeleton'
import Condition from 'components/condition'
import HonestView from 'components/template/honest-view'
const { If } = Condition;

import RelativeExpenseReportDetail from 'containers/expense-report/relative-expense-report-detail'
import ExpenseDetailAlert from 'containers/expense-report/components/expense-detail-alert'
import baseService from 'share/base.service'
import expenseReportService from 'containers/expense-report/expense-report.service'
import 'styles/expense-report/components/expense-detail-header.scss'

class ExpenseDetailHeader extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      honestInfo: {}, //信用详情
      honestModalShow: false,
      isEditing: false,
      bookDate: null,
      bookDateTemp: null,
      isSavingBookDate: false
    }
  }

  componentWillReceiveProps(nextProps) {
    const { info } = nextProps;
    const { honestInfo } = this.state;
    if (info.applicantOID && !honestInfo.creditStatus) {
      //先将creditStatus置为true，防止多次请求该接口
      this.setState({ honestInfo: { creditStatus: true } }, () => {
        this.getHonestInfo(info)
      });
    }
    this.setState({
      bookDate: info.bookDate,
      bookDateTemp: info.bookDate,
    })
  }

  //获取信用详情信息
  getHonestInfo = (info) => {
    const { applicantOID, applicantJobId } = info;
    baseService.getHonestInfo(applicantOID, applicantJobId).then(res => {
      this.setState({ honestInfo: res.data || {} })
    })
  };

  //获取审批状态
  getStatus = () => {
    const { info } = this.props;
    let status = constants.documentStatus;
    let result = {};
    status.map(item => {
      if (item.value === String(info.status) || item.value === String(info.status * 10000 + info.rejectType)) {
        result = item
      }
    });
    return result
  };

  //是否展示挂起
  isShowHangUp = () => {
    const { approvalChains } = this.props;
    let showHangUp = false;
    let approverOID = getQueryUrlParam('approverOID');
    approvalChains && approvalChains.map(chain => {
      if (chain.approverOID === approverOID && chain.pending) {
        showHangUp = true
      }
    });
    return showHangUp
  };

  handleChange = value => {
    this.setState({ bookDateTemp: value });
  };

  onSaveBookDate = () => {
    const { loginCompany, info, user, afterSaveBookDate } = this.props;
    const { bookDateTemp } = this.state;
    let params = {
      "entityOID": info.expenseReportOID,//单据oid
      "approvalOID": user.userOID,//审核人oid
      "entityType": 1002,//单据类型 报销单1002
      "bookDateUpdateType": Number(!!(bookDateTemp)), //更新类型 0 默认(取最终审核当前时间) 1 手工输入时间
      "bookDate": bookDateTemp //记账日期
    };
    this.setState({ isSavingBookDate: true });
    expenseReportService.saveBookDate(params, loginCompany.companyOID).then(res => {
      this.setState({
        isSavingBookDate: false,
        isEditing: false,
        bookDate: res.data ? res.data.bookDate : null
      });
      afterSaveBookDate(res.data ? res.data.bookDate : null);
    }).catch(() => {
      message.error(messages('common.save.filed'));
    })
  };

  render() {
    const { loading, info, applicant, pageFrom, jobInfo, showEditBookDate, showExpenseReportInvoices } = this.props;
    const { honestInfo, honestModalShow, isEditing, isSavingBookDate, bookDate, bookDateTemp } = this.state;
    let warningList = JSON.parse(info.warningList || '[]');
    let currencyPrecision = queryCurrencyPrecision(info.currencyCode);
    let expenseReportStatus = info ? this.getStatus() : {};
    let totalApportionmentAmount = 0;
    showExpenseReportInvoices.map((invoice, index) => {
      invoice.index = index + 1;
      totalApportionmentAmount = addCalculate(
        totalApportionmentAmount,
        invoice.apportionmentAmount || invoice.apportionmentAmount === 0 ? invoice.apportionmentAmount : invoice.washAmount ? 0 : invoice.baseAmount
      );
    });
    let totalWashAmount = 0;
    showExpenseReportInvoices.map((invoice, index) => {
      invoice.index = index + 1;
      totalWashAmount = addCalculate(
        totalWashAmount,
        ['MCD1018', 'MCD1024', 'MCD1221', 'MCD1214', 'MCD1229', 'MCD1053'].includes(invoice.expenseTypeCode) ? invoice.washAmount || invoice.washAmount === 0 ? invoice.washAmount : invoice.baseAmount : 0
      );
    });
    return (
      <div className="expense-detail-header">
        <Skeleton loading={loading}>
          <Row>
            <ExpenseDetailAlert noPrint={info.printFree} warningList={warningList}/>
            <span className="top-info-name">{applicant.fullName}</span>
            <span className="detail-info">
              {/* <If value={honestInfo.creditStatus !== 1001 && info.status !== 1005}> */}
              <If value={honestInfo.creditStatus !== 1001}>
                <a className="honest-info" onClick={() => this.setState({honestModalShow: true})}>
                  {messages('expense-parent-report.key106')/*信用分*/}：{honestInfo.score}
                  <If value={honestInfo.rankFlag}>
                    <span className="ant-divider"/>
                    {messages('expense-parent-report.key107')/*信用等级*/}：{honestInfo.creditRank}
                  </If>
                </a>
              </If>
              {messages('common.user.id')/*工号*/}：{applicant.employeeID}
              <span className="ant-divider"/>
              {messages('common.department')/*部门*/}：
              {this.checkFunctionProfiles('department.full.path.disabled', [true]) ?
                info.applicantDepartmentName : info.applicantDepartmentPath}
              <span className="ant-divider"/>
              {messages('common.user.company')/*员工公司*/}：{info.applicantCompanyName}
              <span className="ant-divider"/>
              {messages('common.currency')/*币种*/}：{info.baseCurrency}
              <span className="ant-divider"/>
              {messages('expense-parent-report.key27'/*还款金额*/)}：
              {(info.status >= 1004 || !info.loanApplicationOID) ?
                `${info.currencyCode || ''} ${this.filterMoney(info.reimbursementAmount, currencyPrecision, true)}` :
                messages('expense-parent-report.key28'/*审核通过后计算*/)}
              <If value={info.createdName !== info.applicantName}>
                <span className="ant-divider"/>
                {messages('expense-parent-report.key29'/*制单人*/)}：
                {info.createdName} {moment(info.createdDate).format('YYYY-MM-DD')}
              </If>
            </span>
          </Row>
          <Row>
            <span className="detail-info detail-info-first">
              {info.formName}：{info.parentBusinessCode ? `${info.parentBusinessCode}-` : ''}{info.businessCode}
            </span>
            <span className="detail-info">
              {messages('common.submit.date')/*提交日期*/}：
              {info.lastSubmittedDate ? moment(info.lastSubmittedDate).format('YYYY-MM-DD') :
                moment(info.createdDate).format('YYYY-MM-DD')}
              <If value={info.submittedBy && info.submittedBy !== applicant.userOID}>
                {messages('expense-parent-report.key97', {arg1: info.submittedName}/*由 {arg1} 代提*/)}
              </If>
            </span>
            <span className="detail-info">
              {messages('common.column.status')/*状态*/}：{expenseReportStatus.text}
            </span>
            <If value={pageFrom === 'auditView' && false}>
              <span className="detail-info">
                {messages('expense-parent-report.key250')/*记账日期*/}：
                {isEditing ?
                  (
                    <Spin spinning={isSavingBookDate} wrapperClassName='book-date-spin'>
                      <DatePicker onChange={this.handleChange} value={bookDateTemp ? moment(bookDateTemp) : null}/>
                      <Popover content={
                        <span>
                          <p className='reset-margin-bottom'>{messages('expense-parent-report.key251')/*若空，则以单据状态置为【审核通过】的日期作为记账日期*/}; </p>
                          <p className='reset-margin-bottom'>{messages('expense-parent-report.key252')/*若有值，则以自定义日期作为记账日期*/}</p>
                        </span>} placement="bottomRight"
                      >
                        <Icon type="info-circle-o" style={{margin: "0 4px"}}/>
                      </Popover>
                      <Button type='primary' size='small' style={{margin: '0 6px'}} onClick={this.onSaveBookDate}>{messages('common.save')/*保存*/}</Button>
                      <Button size='small' onClick={() => this.setState({isEditing: false})}>{messages('common.cancel')/*取消*/}</Button>
                    </Spin>
                  ) :
                  (!!bookDate ? moment(bookDate).format('YYYY-MM-DD') : messages('expense-parent-report.key253')/*最终审核通过日期*/)
                }
                {showEditBookDate && !isEditing && <Icon type="edit" className='book-date' onClick={() => this.setState({isEditing: true})}/>}
              </span>
            </If>
            <If value={info.expenseReportBagCode}>
              <span className="detail-info">{messages('expense-parent-report.key246')/*关联发票袋*/}：{info.expenseReportBagCode}</span>
            </If>
            <If value={this.isShowHangUp()}>
              <Tag style={{ marginLeft: 8 }} color="#505564">{messages('expense-parent-report.key172')/*暂挂*/}</Tag>
            </If>
            <If value={info.carPerson && info.carPerson.id}>
              <span className="detail-info">司机姓名：{info.carPerson && info.carPerson.name}</span>
            </If>
          </Row>
          <RelativeExpenseReportDetail info={info} pageFrom={pageFrom}/>
          <Row>
            <span className="amount">
              {messages('expense-parent-report.key30'/*单据金额*/)}：
              {info.currencyCode}&nbsp;
              {this.filterMoney(info.totalAmount, currencyPrecision)}
              &nbsp;&nbsp;
              {messages('expense-parent-report.key31'/*付款金额*/)}：
              {info.currencyCode}&nbsp;
              {this.filterMoney(info.realPaymentAmount, currencyPrecision)}
              &nbsp;&nbsp;
              {messages('common.base.currency.apportionmentAmount'/*待审批分摊金额*/)}：
              {info.currencyCode}&nbsp;
              {this.filterMoney(totalApportionmentAmount, currencyPrecision)}
              &nbsp;&nbsp;
              {messages('common.base.currency.washAmount'/*餐饮共享金额*/)}：
              {totalWashAmount ? info.currencyCode : ''}&nbsp;
              {totalWashAmount ? this.filterMoney(totalWashAmount, currencyPrecision) : '-'}
            </span>
          </Row>
        </Skeleton>

        <Modal title={messages('expense-parent-report.key110')/*信用查看*/}
               visible={honestModalShow}
               className="honest-view-modal"
               width={900}
               footer={[
                 <Button type={'primary'} onClick={() => this.setState({honestModalShow: false})}>
                   {messages('expense-parent-report.key111')/*关闭*/}
                 </Button>
               ]}
               onCancel={() => this.setState({honestModalShow: false})}>
          <HonestView applicant={applicant} jobId={jobInfo.id}/>
        </Modal>
      </div>
    )
  }
}

ExpenseDetailHeader.propsType = {
  loading: React.PropTypes.bool,
  info: React.PropTypes.object, //报销单详情
  jobInfo: React.PropTypes.object, //岗位信息
  applicant: React.PropTypes.object, //申请人详情
  pageFrom: React.PropTypes.string,
  approvalChains: React.PropTypes.array,
};

function mapStateToProps(state) {
  return {
    loginCompany: state.login.loginCompany,
    user: state.login.user
  }
}

export default connect(mapStateToProps)(ExpenseDetailHeader)
